<template>
    <!--地图挂载dom-->
    <div id="map">
    </div>
</template>

<script>
    //引入依赖
    import {Map, View} from 'ol'
    import {OSM, Vector as VectorSource} from 'ol/source';
    import {Stroke, Style} from 'ol/style';
    import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
    import {GeoJSON, WFS} from 'ol/format';


    export default {
        name: 'ProjectGeoServerWFS',
        data() {
            return {}
        },
        mounted() {
            //初始化地图
            this.map = new Map({
                target: 'map',//指定挂载dom，注意必须是id
                layers: [
                    new TileLayer({
                        source: new OSM()//加载OpenStreetMap
                    })
                ],
                //配置视图
                view: new View({
                    center: [113.24981689453125, 23.126468438108688], //视图中心位置
                    projection: "EPSG:4326", //指定投影
                    zoom: 12   //缩放到的级别
                })
            });

            const vectorSource = new VectorSource();
            const vector = new VectorLayer({
                source: vectorSource,
                style: new Style({
                    stroke: new Stroke({
                        color: '#c771ff',
                        width: 2,
                    }),
                }),
            });

            this.map.addLayer(vector);
            // 生成获取要素的请求
            const featureRequest = new WFS().writeGetFeature({
                srsName: 'EPSG:4326',//坐标系
                featureNS: 'www.openlayers.com',// 注意这个值必须为创建工作区时的命名空间URI
                featurePrefix: 'openlayers',//工作区的名称
                featureTypes: ['province'],//所要访问的图层
                outputFormat: 'application/json',//数据输出格式
                geometryName: 'the_geom',//几何体的名称
                maxFeatures: 50,//最大请求数量
            });

            // 发送post请求获取图层要素
            fetch('http://localhost:8080/geoserver/wfs', {
                method: 'POST',
                body: new XMLSerializer().serializeToString(featureRequest),
            }).then((response) => {
                return response.json();
            }).then((json) => {
                console.log(json)
                const features = new GeoJSON().readFeatures(json);
                vectorSource.addFeatures(features);
                this.map.getView().fit(vectorSource.getExtent());
            });
        },
        methods: {}
    }
</script>

<style scoped>
    #map {
        width: 100%;
        height: 100%;
    }
</style>
